'use client'

import React, { useState } from 'react'
import {
    Card,
    Button,
    Space,
    Typography,
    List,
    Tag,
    Spin,
    Alert,
    Descriptions,
    Collapse,
    Statistic,
    Row,
    Col
} from 'antd'
import {
    PlayCircleOutlined,
    ReloadOutlined,
    DatabaseOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import { useApiClient, useApiClientInfo } from '@/hooks/useApiClient'
import { useDevToolsStore } from '@/stores/devToolsStore'
import { Dataset } from '@/types/dataset'
import { Task } from '@/types/task'

const { Title, Text, Paragraph } = Typography
const { Panel } = Collapse

export function MockDataTester() {
    const [loading, setLoading] = useState(false)
    const [testResults, setTestResults] = useState<any[]>([])
    const [datasets, setDatasets] = useState<Dataset[]>([])
    const [selectedDataset, setSelectedDataset] = useState<Dataset | null>(null)
    const [tasks, setTasks] = useState<Task[]>([])

    const apiClient = useApiClient()
    const clientInfo = useApiClientInfo()
    const { mockDataMode, setMockDataMode } = useDevToolsStore()

    // 测试数据集获取
    const testGetDatasets = async () => {
        setLoading(true)
        try {
            const startTime = Date.now()
            const result = await apiClient.getDatasets()
            const duration = Date.now() - startTime

            setDatasets(result)
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getDatasets',
                status: 'success',
                duration,
                result: `获取到 ${result.length} 个数据集`,
                data: result
            }])
        } catch (error) {
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getDatasets',
                status: 'error',
                error: error instanceof Error ? error.message : 'Unknown error'
            }])
        } finally {
            setLoading(false)
        }
    }

    // 测试单个数据集获取
    const testGetDataset = async (datasetId: string) => {
        setLoading(true)
        try {
            const startTime = Date.now()
            const result = await apiClient.getDataset(datasetId)
            const duration = Date.now() - startTime

            setSelectedDataset(result)
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getDataset',
                status: 'success',
                duration,
                result: `获取数据集: ${result.name}`,
                data: result
            }])
        } catch (error) {
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getDataset',
                status: 'error',
                error: error instanceof Error ? error.message : 'Unknown error'
            }])
        } finally {
            setLoading(false)
        }
    }

    // 测试任务获取
    const testGetTasks = async (datasetId: string) => {
        setLoading(true)
        try {
            const startTime = Date.now()
            const result = await apiClient.getTasks(datasetId)
            const duration = Date.now() - startTime

            setTasks(result)
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getTasks',
                status: 'success',
                duration,
                result: `获取到 ${result.length} 个任务`,
                data: result
            }])
        } catch (error) {
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'getTasks',
                status: 'error',
                error: error instanceof Error ? error.message : 'Unknown error'
            }])
        } finally {
            setLoading(false)
        }
    }

    // 测试任务执行
    const testStartTask = async (taskId: string) => {
        setLoading(true)
        try {
            const startTime = Date.now()
            const result = await apiClient.startTask(taskId, {})
            const duration = Date.now() - startTime

            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'startTask',
                status: 'success',
                duration,
                result: `任务执行完成: ${result.status}`,
                data: result
            }])
        } catch (error) {
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'startTask',
                status: 'error',
                error: error instanceof Error ? error.message : 'Unknown error'
            }])
        } finally {
            setLoading(false)
        }
    }

    // 测试健康检查
    const testHealthCheck = async () => {
        setLoading(true)
        try {
            const startTime = Date.now()
            const result = await apiClient.healthCheck()
            const duration = Date.now() - startTime

            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'healthCheck',
                status: 'success',
                duration,
                result: `健康状态: ${result.status}`,
                data: result
            }])
        } catch (error) {
            setTestResults(prev => [...prev, {
                id: Date.now(),
                test: 'healthCheck',
                status: 'error',
                error: error instanceof Error ? error.message : 'Unknown error'
            }])
        } finally {
            setLoading(false)
        }
    }

    // 清空测试结果
    const clearResults = () => {
        setTestResults([])
        setDatasets([])
        setSelectedDataset(null)
        setTasks([])
    }

    // 运行所有测试
    const runAllTests = async () => {
        clearResults()
        await testHealthCheck()
        await testGetDatasets()

        if (datasets.length > 0) {
            const firstDataset = datasets[0]
            await testGetDataset(firstDataset.id)
            await testGetTasks(firstDataset.id)

            if (tasks.length > 0) {
                await testStartTask(tasks[0].id)
            }
        }
    }

    return (
        <div style={{ padding: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
                {/* API客户端信息 */}
                <Card size="small" title="API客户端信息">
                    <Descriptions size="small" column={2}>
                        <Descriptions.Item label="模式">{clientInfo.mode}</Descriptions.Item>
                        <Descriptions.Item label="使用模拟API">
                            <Tag color={clientInfo.useMockApi ? 'green' : 'red'}>
                                {clientInfo.useMockApi ? '是' : '否'}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="模拟数据模式">{clientInfo.mockDataMode}</Descriptions.Item>
                        <Descriptions.Item label="开发模式">
                            <Tag color={clientInfo.isDevMode ? 'blue' : 'default'}>
                                {clientInfo.isDevMode ? '是' : '否'}
                            </Tag>
                        </Descriptions.Item>
                    </Descriptions>
                </Card>

                {/* 快速测试按钮 */}
                <Card size="small" title="快速测试">
                    <Space wrap>
                        <Button
                            type="primary"
                            icon={<PlayCircleOutlined />}
                            onClick={runAllTests}
                            loading={loading}
                        >
                            运行所有测试
                        </Button>
                        <Button
                            icon={<DatabaseOutlined />}
                            onClick={testGetDatasets}
                            loading={loading}
                        >
                            测试数据集
                        </Button>
                        <Button
                            icon={<ClockCircleOutlined />}
                            onClick={testHealthCheck}
                            loading={loading}
                        >
                            健康检查
                        </Button>
                        <Button
                            icon={<ReloadOutlined />}
                            onClick={clearResults}
                        >
                            清空结果
                        </Button>
                    </Space>
                </Card>

                {/* 模拟数据模式切换 */}
                <Card size="small" title="模拟数据模式">
                    <Space wrap>
                        {['default', 'large', 'error', 'empty', 'slow'].map(mode => (
                            <Button
                                key={mode}
                                type={mockDataMode === mode ? 'primary' : 'default'}
                                onClick={() => setMockDataMode(mode)}
                                size="small"
                            >
                                {mode}
                            </Button>
                        ))}
                    </Space>
                    <Paragraph style={{ marginTop: 8, marginBottom: 0 }}>
                        <Text type="secondary">
                            切换不同的模拟数据模式来测试各种场景
                        </Text>
                    </Paragraph>
                </Card>

                {/* 测试结果统计 */}
                {testResults.length > 0 && (
                    <Card size="small" title="测试统计">
                        <Row gutter={16}>
                            <Col span={6}>
                                <Statistic
                                    title="总测试数"
                                    value={testResults.length}
                                    prefix={<DatabaseOutlined />}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="成功"
                                    value={testResults.filter(r => r.status === 'success').length}
                                    valueStyle={{ color: '#3f8600' }}
                                    prefix={<CheckCircleOutlined />}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="失败"
                                    value={testResults.filter(r => r.status === 'error').length}
                                    valueStyle={{ color: '#cf1322' }}
                                    prefix={<ExclamationCircleOutlined />}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="平均耗时"
                                    value={testResults
                                        .filter(r => r.duration)
                                        .reduce((sum, r) => sum + r.duration, 0) /
                                        testResults.filter(r => r.duration).length || 0
                                    }
                                    suffix="ms"
                                    precision={0}
                                />
                            </Col>
                        </Row>
                    </Card>
                )}

                {/* 数据集列表 */}
                {datasets.length > 0 && (
                    <Card size="small" title={`数据集列表 (${datasets.length})`}>
                        <List
                            size="small"
                            dataSource={datasets}
                            renderItem={(dataset) => (
                                <List.Item
                                    actions={[
                                        <Button
                                            key="detail"
                                            size="small"
                                            onClick={() => testGetDataset(dataset.id)}
                                        >
                                            详情
                                        </Button>,
                                        <Button
                                            key="tasks"
                                            size="small"
                                            onClick={() => testGetTasks(dataset.id)}
                                        >
                                            任务
                                        </Button>
                                    ]}
                                >
                                    <List.Item.Meta
                                        title={
                                            <Space>
                                                <span>{dataset.name}</span>
                                                <Tag color={dataset.type === '3D' ? 'blue' : 'green'}>
                                                    {dataset.type}
                                                </Tag>
                                            </Space>
                                        }
                                        description={dataset.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </Card>
                )}

                {/* 测试结果 */}
                {testResults.length > 0 && (
                    <Card size="small" title="测试结果">
                        <List
                            size="small"
                            dataSource={testResults.slice().reverse()} // 最新的在前
                            renderItem={(result) => (
                                <List.Item>
                                    <Collapse style={{ width: '100%' }}>
                                        <Panel
                                            header={
                                                <Space>
                                                    <Tag color={result.status === 'success' ? 'green' : 'red'}>
                                                        {result.test}
                                                    </Tag>
                                                    <span>{result.result || result.error}</span>
                                                    {result.duration && (
                                                        <Text type="secondary">{result.duration}ms</Text>
                                                    )}
                                                </Space>
                                            }
                                            key={result.id}
                                        >
                                            {result.status === 'error' ? (
                                                <Alert
                                                    message="测试失败"
                                                    description={result.error}
                                                    type="error"
                                                    showIcon
                                                />
                                            ) : (
                                                <pre style={{
                                                    background: '#f5f5f5',
                                                    padding: 8,
                                                    borderRadius: 4,
                                                    fontSize: 12,
                                                    maxHeight: 200,
                                                    overflow: 'auto'
                                                }}>
                                                    {JSON.stringify(result.data, null, 2)}
                                                </pre>
                                            )}
                                        </Panel>
                                    </Collapse>
                                </List.Item>
                            )}
                        />
                    </Card>
                )}

                {loading && (
                    <div style={{ textAlign: 'center', padding: 20 }}>
                        <Spin size="large" tip="执行测试中..." />
                    </div>
                )}
            </Space>
        </div>
    )
}

export default MockDataTester